#include <stdio.h>
#include <errno.h>
#include <string.h>

#include <sys/types.h>
#include <sys/shm.h>
#include <sys/ipc.h>

typedef __uint8_t uint8_t;
typedef __uint16_t uint16_t;
typedef __uint32_t uint32_t;
typedef __uint64_t uint64_t;

typedef struct {
    uint32_t len;
    uint32_t rsv;
    uint8_t  data[0]; 
} GshmNodeHead;

#define GSHM_POOL_NODE_SIZE (sizeof(GshmNodeHead) + 1024)
#define GSHM_POOL_NODE_NUM 1000
#define GSHM_POOL_KEY 1

uint8_t *g_shmMemStartAddr = NULL;

static inline void *GetGshmNodeByIndex(uint32_t id)
{
    if (g_shmMemStartAddr == NULL) {
        return NULL;
    }

    return g_shmMemStartAddr + GSHM_POOL_NODE_SIZE * id;
}

void *GetGshmSharedMempool()
{
    int shmId = shmget(GSHM_POOL_KEY, GSHM_POOL_NODE_SIZE * GSHM_POOL_NODE_NUM, SHM_R | SHM_W | IPC_CREAT);
    if (shmId == -1) {
        printf("shmget fail errno = [%d]%s\r\n", errno, strerror(errno));
        return NULL;
    }

    void *shm = shmat(shmId, NULL, 0);
    if (shm == (void*)-1) {
        printf("shmat fail errno = [%d]%s\r\n", errno, strerror(errno));
        return NULL;
    }

    printf("get shared mempool succ. shmId = %u shm = %p\r\n", shmId, shm);

    return shm;
}

int main()
{
    g_shmMemStartAddr = (uint8_t*)GetGshmSharedMempool();

    printf("node10 = %p\r\n", GetGshmNodeByIndex(10));
    return 0;
}